package com.lingkang.sales.config.flowable;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import java.util.Date;
import javax.sql.DataSource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author linke
 * @date 2020/11/24 22:15
 * @description
 */
@Slf4j
@Configuration
public class FlowableConfig {

  /**
   * 参数1为终端ID，参数2为数据中心ID
   * 反推生成时间snowflake.getGenerateDateTime(1331265965442338816L)
   */
  private static Snowflake snowflake = IdUtil.createSnowflake(1, 1);

  @Autowired
  @Qualifier("flowableDataSource")
  private DataSource dataSource;

  @Bean
  public ProcessEngineConfiguration processEngineConfiguration() {
    ProcessEngineConfiguration configuration = new StandaloneProcessEngineConfiguration();
    configuration.setDataSource(dataSource);
    //#关闭定时任务JOB
    configuration.setAsyncExecutorActivate(false);
    configuration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
    configuration.setIdGenerator(() -> snowflakeId());
    // 解决流程图乱码
    configuration.setActivityFontName("宋体");
    configuration.setLabelFontName("宋体");
    configuration.setAnnotationFontName("宋体");
    return configuration;
  }

  /**
   * 雪花算法，生成唯一数字id
   */
  @Bean
  public String snowflakeId() {
    return snowflake.nextIdStr();
  }


  @Bean
  public ProcessEngine processEngine() {
    return processEngineConfiguration().buildProcessEngine();
  }

  @Bean
  public RepositoryService repositoryService() {
    return processEngine().getRepositoryService();
  }

  @Bean
  public RuntimeService runtimeService() {
    return processEngine().getRuntimeService();
  }

  @Bean
  public TaskService taskService() {
    return processEngine().getTaskService();
  }

  public static void main(String[] args) {
    Date date=new Date();
    System.out.println(date);
    System.out.println(date.getTime());
    System.out.println(new Date(1606233249780L));
    System.out.println(snowflake.nextIdStr());
    System.out.println(snowflake.getGenerateDateTime(1331265965442338816L));
  }
}
